class DB {
  constructor() {
    this.mysql = require('mysql');
    this.config = require('./db.config');
  }

  query(sql, params) {
    return new Promise((resolve, reject) => {
      //创建mysql连接对象
      const connection = this.mysql.createConnection(this.config);
      //开启连接
      connection.connect(err => {
        if (err) {
          console.log('数据库连接失败');
          reject(err);
        }
        console.log('数据库连接成功')
      })
      //执行sql语句
      connection.query(sql, params, (err, results, fields) => {
        if (err) {
          console.log('sql语句执行失败');
          reject(err);
        }
        resolve({
          results,
          fields
        })
      })
      //关闭语句
      connection.end(err => {
        if (err) {
          console.log('数据库关闭失败');
          reject(err);
        }
        console.log('数据库关闭成功')
      })
    })
  }
}

module.exports = new DB();